package com.lin.wx.official.account.service.impl;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.lin.wx.official.account.common.WXSHA1;
import com.lin.wx.official.account.common.WxBizMsgCrypt;
import com.lin.wx.official.account.model.vo.WxBodyVO;
import com.lin.wx.official.account.service.IWxManagerBiz;
import com.lin.wx.official.account.service.IWxMessageBiz;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author lhm
 * @date 2024/6/5 10:02
 */
@Slf4j
@Service
public class WxManagerBiz implements IWxManagerBiz {
    @Resource
    private IWxMessageBiz wxMessageBiz;


    @Override
    public String verifyToken(String appId, WxBodyVO bodyVO) throws Exception {
        log.info("开发者服务器验签，appid：{}，消息体：{}", appId, bodyVO);

        // 验签 token -> 不是AccessToken，而是对应于微信公众号自定义配置的token
        String sha1 = WXSHA1.getSHA1("AAAA", bodyVO.getTimestamp(), bodyVO.getNonce(), "");
        log.info("通过工具验签之后的加密串：{}", sha1);
        return bodyVO.getSignature().equals(sha1) ? bodyVO.getEchostr() : StringUtils.EMPTY;
    }

    @Override
    public String callbackXml(String appId, String messageXml, WxBodyVO bodyVO) throws Exception {
        log.info("接收到微信的推文：{}，额外参数：{}", messageXml, bodyVO);
        try {
            // 是否加密
            if ("aes".equalsIgnoreCase(bodyVO.getEncrypt_type())) {
                // 获取公众号配置
                WxBizMsgCrypt pc = new WxBizMsgCrypt("AAAA", "gwQikEYF2YQ5CS0xBD9cOWZ2Zmt5kmHidIonfqxjrsl", appId);
                messageXml = pc.decryptMsg(bodyVO.getMsg_signature(), bodyVO.getTimestamp(), bodyVO.getNonce(), messageXml);
            }
        } catch (Exception e) {
            log.error("解析微信加密报文失败:【{}】", e);
        }

        // 解析消息体
        try {
            WxMpXmlMessage message = WxMpXmlMessage.fromXml(messageXml);
            return wxMessageBiz.handleXmlMessage(appId, message);
        } catch (Exception e) {
            log.error("处理微信消息失败:【{}】", e.getMessage());
            e.printStackTrace();
            // 业务处理失败的候选操作
            return "消息处理异常";
        }
    }

    @Override
    public String getOpenId(String code, String appId) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
        // 需要携带appId -> 后台根据配置appId去获取对应的密匙
        String result = HttpUtil.get(String.format(url, "wxf8819759cf8d0daa", "de14c362735b9d4cb7a24f1d36363508", code));
        JSONObject object = JSONObject.parse(result);
        String openId = object.getString("openid");
        if (StringUtils.isEmpty(openId)) {
            throw new RuntimeException("获取openId失败");
        }
        return openId;
    }
}
